﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Configuration;
using System.Web.Mvc;
using System.ComponentModel;
using EIIS.Infrastructure.Service.System.Authority;
using EIIS.Infrastructure.Model.System.Authority;
using EIIS.Presentation.Controllers.CommonSupport;
using EIIS.Presentation.Controllers.ViewModel;
using EIIS.Common.Jsons;
using EIIS.FrameWork.Attributes;

namespace EIIS.Presentation.Controllers.System.Authority
{
    [Description("角色管理")]
    public class RoleController : BaseController
    {
        public IRoleManager RoleManager { get; set; }
        public IActionPermissionManager ActionPermissionManager { get; set; }
        public IMenuManager MenuManager { get; set; }

        [Description("角色管理页面")]
        [ViewPage]
        public ActionResult Index()
        {
            return View();
        }

        public ActionResult LoadAll(int page, int rows, string order, string sort)
        {
            long total = 0;
            IList<Role> ilist = RoleManager.LoadAllWithPage(out total, page, rows, order, sort).ToList();
            var query = ilist.Select(r => new
            {
                r.Id,
                r.Name,
                r.Description,
                r.State,
                Menus = r.MenuNodes.Select(m => new { m.Id }),
                Persons = r.Persons.Select(p => new { p.Id }),
                Permissions = r.ActionPermissions.Select(a => new { a.Id })
            });


            return this.JsonFormat(new GridData { total = total, rows = query.ToList() });
        }

        [Description("新增角色")]
        [Function(ButtonID = "btnAdd")]
        public ActionResult Add()
        {
            Role entity = new Role();
            this.ViewData["entity"] = entity;
            return View();
        }

        [Description("修改角色")]
        [Function(ButtonID = "btnUpdate")]
        public ActionResult Edit(string id)
        {
            Role entity = this.RoleManager.Get(id);
            this.ViewData["entity"] = entity;
            return View();
        }

        [Description("删除角色")]
        [Function(ButtonID = "btnDelete")]
        public ActionResult Delete(IList<string> idList)
        {
            MessageInfo msg = new MessageInfo();
            msg.IsSuccess = true;
            msg.Message = "删除成功";
            RoleManager.Delete(idList.Cast<object>().ToList());
            return Json(msg);
        }

        [Description("保存角色")]
        [HttpPost]
        public ActionResult Save(Role entity)
        {
            MessageInfo msg = new MessageInfo();
            if (string.IsNullOrEmpty(entity.Id))//新增
            {
                if (RoleManager.IsExistWithName(entity.Name, "-1", ""))
                {
                    msg.IsSuccess = false;
                    msg.Message = "新增失败，已存在该角色名称的记录";
                    return Json(msg);
                }
                entity.Id = Guid.NewGuid().ToString();

                string strInheritRoleId = Request["InheritRoleId"];
                RoleManager.SaveRole(entity,strInheritRoleId);
            }
            else
            {
                var model = RoleManager.Get(entity.Id);
                if (RoleManager.IsExistWithName(entity.Name, entity.Id, ""))
                {
                    msg.IsSuccess = false;
                    msg.Message = "修改失败，已存在该角色名称的记录";
                    return Json(msg);
                }
                model.Name = entity.Name;
                model.State = entity.State;
                model.Description = entity.Description;
                RoleManager.Update(model);
            }
            msg.IsSuccess = true;
            msg.Message = "保存成功";
            return Json(msg, "text/html", JsonRequestBehavior.AllowGet);
        }

        [Description("返回角色状态")]
        public ActionResult GetRoleState(string id)
        {
            var ilist = EnumDescription.ToList<RoleState>();
            List<combobox_data> list = ilist.ToList().ConvertAll<combobox_data>(d => { return new combobox_data() { id = d.Value.ToString(), text = d.Key, selected = (d.Value.ToString() == id ? true : false) }; });
            return Json(list);
        }

        public ActionResult GetMenu(string id)
        {
            Role role = RoleManager.Get(id);
            List<MenuNode> list = new List<MenuNode>();
            if (role.MenuNodes.Count > 0)
            {
 
            }
            return View();
        }

        //保存角色对应的菜单
        public ActionResult SaveMenu()
        {
            string strRoleId = Request["RId"];
            string strMenuId = Request["MId"];
            MessageInfo msg = new MessageInfo();
            if (!string.IsNullOrEmpty(strRoleId))
            {
                string[] MenuIds = strMenuId.Split(',');
                Role role = RoleManager.Get(strRoleId);
                role.MenuNodes.Clear();
                foreach (string tempMenuId in MenuIds)
                {
                    if (!string.IsNullOrEmpty(tempMenuId))
                    {
                        MenuNode menuNode = MenuManager.Get(tempMenuId);
                        if (menuNode != null)
                            role.MenuNodes.Add(menuNode);
                    }
                }
                RoleManager.SaveOrUpdate(role);
                msg.IsSuccess = true;
                msg.Message = "保存成功";
                return Json(msg);
            }
            else
            {
                msg.IsSuccess = false;
                msg.Message = "请先选择一个角色再保存";
                return Json(msg);
            }
        }

        //保存角色对应的功能权限
        public ActionResult SavePermission()
        {
            string strRoleId = Request["RId"];
            string strPermissionId = Request["PId"];
            MessageInfo msg = new MessageInfo();
            if (!string.IsNullOrEmpty(strRoleId))
            {
                string[] PermissionIds = strPermissionId.Split(',');
                Role role = RoleManager.Get(strRoleId);
                role.ActionPermissions.Clear();
                foreach (string tempPermissionId in PermissionIds)
                {
                    if (!string.IsNullOrEmpty(tempPermissionId))
                    {
                        ActionPermission actionPermission = ActionPermissionManager.Get(tempPermissionId);
                        if (actionPermission != null)
                        {
                            role.ActionPermissions.Add(actionPermission);
                        }
                    }
                }
                RoleManager.SaveOrUpdate(role);
                msg.IsSuccess = true;
                msg.Message = "保存成功";
                return Json(msg);
            }
            else
            {
                msg.IsSuccess = false;
                msg.Message = "请先选择一个角色再保存";
                return Json(msg);
            }
        }
    }
}
